const qiniuUploader = require("./qiniuUploader");
const benUploader = require("./beidiUploader");
import $H from '@/common/free-lib/request.js';
import $C from '@/common/free-lib/config.js';
//七牛云上传文件命名

export const randomChar = function(qianzhui, l, url = "") {
	const x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
	let tmp = "";
	let time = new Date();
	for (let i = 0; i < l; i++) {
		tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
	}
	return (
		qianzhui + "/" +
		url +
		time.getTime() +
		tmp
	);
}
// 上传
export const qiniuUpload = function(requestInfo) {
	return new Promise((resolve, reject) => {
		if (Array.isArray(requestInfo.files)) {



			let len = requestInfo.files.length;
			let fileList = new Array;
			var url = 'banmi.php/Upload/upload_api'

			let requestParams = {
				user_id: uni.getStorageSync('user_id'),
				token: uni.getStorageSync('token'),
			};
			$H.post(url, 'app', {
				token: true,
				datalist: requestParams,

			}).then(ret => {

				var oss = ret.data.data.oss

				var token = ret.data.data.token;
				var qnRes = {
					"token": token,
					"region": ret.data.data.region,
				}
				if (oss == 0) { //bendi
					ben_upload(0);
					return 2;
				}


				uploadFile(0);

				function ben_upload(i) {
					let item = requestInfo.files[i];
					
					if (uni.getStorageSync('platform')=='H5') {
						var domain = window.location.protocol+"//"+window.location.host+'/';
						 if (domain.indexOf("localhost:") == -1 ) {
							$C.baseUrl= domain;  
						 
						 }  
					}  
			 
					
					var url = $C.baseUrl + 'banmi.php/upload/upload';

			  
					if (requestInfo.typeo == 'mp4') {
						var updateUrl = randomChar('video', 10, qnRes.folderPath) + '.' +
							requestInfo.fileExtension;
					} else {
						var updateUrl = randomChar(requestInfo.typeo, 10, qnRes.folderPath);
					}

					let fileData = {
						fileIndex: i,
						
						files: requestInfo.files,
					};


					benUploader.upload(item.path, (res) => {

						fileData.url = res.imageURL;
						requestInfo.onEachUpdate && requestInfo.onEachUpdate({
							url: res.imageURL,
							...fileData
						});
						fileList.push(res.imageURL);
						if (len - 1 > i) {
							benUploader(i + 1);
						} else {
							resolve(fileList);
						}
					}, (error) => {

						reject(error);
					}, {
						region: url, //地区
						domain: qnRes.visitPrefix, // bucket 域名，下载资源时用到。
						key: updateUrl,
						uptoken: qnRes.token, // 由其他程序生成七牛 uptoken
						uptokenURL: 'UpTokenURL.com/uptoken' // 上传地址
					}, (res) => {

						requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object
							.assign({}, fileData, res));

					});


 


				}

				function uploadFile(i) {

					let item = requestInfo.files[i];
					if (requestInfo.typeo == 'mp4') {
						var updateUrl = randomChar('video', 10, qnRes.folderPath) + '.' +
							requestInfo.fileExtension;
					} else {
						var updateUrl = randomChar(requestInfo.typeo, 10, qnRes.folderPath);
					}

					let fileData = {
						fileIndex: i,
						files: requestInfo.files,
					};


					if (item.path) {
						fileData.path = item.path;
					}

					if (item.size) {
						fileData.size = item.size;
					}
					if (item.type) {
						fileData.type = item.type;
					}


					if (item.name) {
						fileData.name = item.name;
						let nameArr = item.name.split(".");
						updateUrl += "." + nameArr[nameArr.length - 1];
					}
					if (item.duration) {
						fileData.duration = item.duration;
					}
					if (item.height) {
						fileData.height = item.height;
					}
					if (item.width) {
						fileData.width = item.width;
					}

					// 交给七牛上传
					qiniuUploader.upload(item.path, (res) => {

						fileData.url = res.imageURL;
						requestInfo.onEachUpdate && requestInfo.onEachUpdate({
							url: res.imageURL,
							...fileData
						});
						fileList.push(res.imageURL);
						if (len - 1 > i) {
							uploadFile(i + 1);
						} else {
							resolve(fileList);
						}
					}, (error) => {

						reject(error);
					}, {
						region: qnRes.region || 'SCN', //地区
						domain: qnRes.visitPrefix, // bucket 域名，下载资源时用到。
						key: updateUrl,
						uptoken: qnRes.token, // 由其他程序生成七牛 uptoken
						uptokenURL: 'UpTokenURL.com/uptoken' // 上传地址
					}, (res) => {

						requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object
							.assign({}, fileData, res));

						// console.log('上传进度', res.progress)
						// console.log('已经上传的数据长度', res.totalBytesSent)
						// console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
					});
				}
			});

		} else {
			reject({
				errMsg: "files 必须是数组类型",
				statusCode: 0
			});
		};
	});
}
// 服务器URL上传
export const urlUpload = function(requestInfo, dataFactory) {
	return new Promise((resolve, reject) => {
		// 本地文件上传去掉默认Content-Type
		if (requestInfo.header['Content-Type']) {
			delete requestInfo.header['Content-Type'];
		}
		// 本地文件上传去掉默认Content-Type
		if (requestInfo.header['content-type']) {
			delete requestInfo.header['content-type'];
		}
		if (Array.isArray(requestInfo.files)) {
			// #ifdef APP-PLUS || H5
			let files = [];
			let fileData = {
				files: requestInfo.files,
				name: requestInfo.name || "file"
			};
			requestInfo.files.forEach(item => {
				files.push({
					uri: item.path,
					name: requestInfo.name || "file"
				});
			});
			let config = {
				url: requestInfo.url,
				files: files,
				header: requestInfo.header, //加入请求头
				success: (response) => {
					//是否用外部的数据处理方法
					if (requestInfo.isFactory && dataFactory) {
						//数据处理
						dataFactory({
							...requestInfo,
							response: response,
						}).then(data => {
							requestInfo.onEachUpdate && requestInfo.onEachUpdate({
								data: data,
								...fileData
							});
							resolve(data);
						}, err => {
							reject(err);
						});
					} else {
						requestInfo.onEachUpdate && requestInfo.onEachUpdate({
							data: response,
							...fileData
						});
						resolve(response);
					}
				},
				fail: (err) => {
					reject(err);
				}
			};
			if (requestInfo.data) {
				config.formData = requestInfo.data;
			}
			const uploadTask = uni.uploadFile(config);
			uploadTask.onProgressUpdate(res => {
				requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({},
					fileData, res));
			});
			// #endif
			// #ifdef MP
			const len = requestInfo.files.length - 1;
			let fileList = new Array;
			fileUpload(0);

			function fileUpload(i) {
				let item = requestInfo.files[i];
				let fileData = {
					fileIndex: i,
					files: requestInfo.files,
				};
				if (item.path) {
					fileData.path = item.path;
				}
				if (item.size) {
					fileData.size = item.size;
				}
				if (item.type) {
					fileData.type = item.type;
				}
				if (item.name) {
					fileData.name = item.name;
				}
				if (item.duration) {
					fileData.duration = item.duration;
				}
				if (item.height) {
					fileData.height = item.height;
				}
				if (item.width) {
					fileData.width = item.width;
				}
				let config = {
					url: requestInfo.url,
					filePath: item.path,
					header: requestInfo.header, //加入请求头
					name: requestInfo.name || "file",
					success: (response) => {
						//是否用外部的数据处理方法
						if (requestInfo.isFactory && dataFactory) {
							//数据处理
							dataFactory({
								...requestInfo,
								response: response,
							}).then(data => {
								fileList.push(data);
								requestInfo.onEachUpdate && requestInfo.onEachUpdate({
									data: data,
									...fileData
								});
								if (len <= i) {
									resolve(fileList);
								} else {
									fileUpload(i + 1);
								}
							}, err => {
								reject(err);
							});
						} else {
							requestInfo.onEachUpdate && requestInfo.onEachUpdate({
								data: response,
								...fileData
							});
							fileList.push(response);
							if (len <= i) {
								resolve(fileList);
							} else {
								fileUpload(i + 1);
							}
						}
					},
					fail: (err) => {
						reject(err);
					}
				};
				if (requestInfo.data) {
					config.formData = requestInfo.data;
				}
				const uploadTask = uni.uploadFile(config);
				uploadTask.onProgressUpdate(res => {
					requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(Object.assign({},
						fileData, res));
				});
			}
			// #endif
		} else {
			reject({
				errMsg: "files 必须是数组类型",
				statusCode: 0
			});
		}
	});
}
